<?php

namespace App\Http\Controllers\Api;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Illuminate\Http\Request;
use OSS\OssClient;
use OSS\Core\OssException;
class CommonController extends BaseController
{

    public function oss_token(){
        //构建阿里云客户端时需要设置AccessKey ID和AccessKey Secret。
        AlibabaCloud::accessKeyClient(env('OSS_ACCESS_ID',''), env('OSS_ACCESS_SECRET',''))
            ->regionId(env('OSS_REGION_ID',''))
            ->asDefaultClient();
        //设置参数，发起请求。关于参数含义和设置方法，请参见《API参考》。
        try {
            $result = AlibabaCloud::rpc()
                ->product('Sts')
                ->scheme('https') // https | http
                ->version('2015-04-01')
                ->action('AssumeRole')
                ->method('POST')
                ->host('sts.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => env('OSS_REGION_ID',''),
                        'RoleArn' => env('OSS_RoleARN',''),
                        'RoleSessionName' => "lhb",
                    ],
                ])
                ->request();
            $data = $result->toArray();
            return response()->json(['code'=>1,'data'=>$data]);
        } catch (ClientException $e) {
            return response()->json(['code'=>0,'msg'=>$e->getErrorMessage()]);
        } catch (ServerException $e) {
            return response()->json(['code'=>0,'msg'=>$e->getErrorMessage()]);
        }
    }


    public function upload(Request $request){
        $dir=$request->input('name','');
        if(!$dir) return response()->json(['code'=>0,'msg'=>'请上传目录参数']);
        $file = $request->file('file');
        $fileSuffix=$file->getClientOriginalExtension();
        $filePath = $file->getRealPath();
        $strFilter=array("jpeg","gif","jpg","png","bmp","pic");
        if(!in_array($fileSuffix,$strFilter)) return response()->json(['code'=>0,'msg'=>'请上传正确图片类型']);
        $accessKeyId = env('OSS_ACCESS_ID','');
        $accessKeySecret = env('OSS_ACCESS_SECRET','');
        $endpoint = env('OSS_ENDPOINT','');
        $bucket=env('OSS_BUCKET','');
        $object='cartoon/'.$dir.'/'.date('Y-m-d',time()).'/'.time().rand_code(4).'.'.$fileSuffix;
        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket, $object, $filePath);
        } catch(OssException $e) {
            return response()->json(['code'=>0,'msg'=>'上传失败，错误信息为'.$e->getErrorMessage()]);
            return;
        }
        return response()->json(['code'=>0,'data'=>$object]);
    }




}
